/**
 * name: api-Class
 * description: request处理基础类
 */
import store from '../store/index';
const BASE_URL = process.env.NODE_ENV === 'development' ? '/api' : '/student'; // 请求接口服务器
let isLoading = false;

/**
 * 请求接口
    url: '',
	data: null,
	method: 'GET',
	needToken: true, // 是否需要token
	header: {'content-type': 'application/json'}
	completeUrl: false // 是否为完整的请求url，即不需要使用设定的BASE_URL
 */
function requestBase(options) {
	const token = store.getters.token;
	if (options.needToken === null || options.needToken === undefined) {
		options.needToken = true
	}
	setTimeout(() => {
		if (isLoading && token) {
			uni.hideLoading();
			uni.showToast({
				title: '请求超时',
				icon: 'none',
			});
			isLoading = false;
		}
	}, 10000);

	function serialize (obj, prefix) {
	  const str = []
	  let p
	  if (obj.length === 0) {
		//  str.push(encodeURIComponent(prefix) + '=1')
	  } else {
		for (p in obj) {
		  if (obj.hasOwnProperty(p)) {
			const k = prefix ? prefix + '[' + p + ']' : p
			let v = obj[p]
			if (v instanceof Date) {
			  v = parseTime(v)
			}
			if(v !== null && typeof v === 'object'){
				str.push(serialize(v, k));
			}else{
				str.push(encodeURIComponent(k) + '=' + encodeURIComponent(v))
			}
		  }
		}
	  }

	  return str.join('&')
	}
	return new Promise((resolve, reject) => {
		let path = BASE_URL + options.url;
		let params = {};
		let header = options.header || {
			'content-type': 'application/json'
		};

		if (options.completeUrl) {
			path = options.url;
		}
		// 需要登录态时
		if (options.needToken) {
			// params.token = token;
			header['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
			// 登录态失效时
			// if (!token) {
			// 	uni.showToast({
			// 		title: '登录态实效，请重新登录',
			// 		icon: 'none',
			// 		mask: true,
			// 	});
			// 	uni.clearStorageSync();
			// 	setTimeout(() => {
			// 		let pages = getCurrentPages(); // 当前页面
			// 		let beforePage = pages[pages.length - 1]; // 前一个页面
			// 		let currentRouter = beforePage && beforePage.route;
			// 		// let options = Qs.stringify(beforePage && beforePage.options);
			// 		let pageOptions = beforePage && beforePage.options;
			// 		if (currentRouter && currentRouter.indexOf('login/login') == -1) {
			// 			uni.reLaunch({
			// 				url: '/pages/login/login?page=' + encodeURIComponent((currentRouter || '') + (pageOptions ? '_' +
			// 					pageOptions : '')),
			// 			});
			// 		}
			// 	}, 2000);
			// 	return;
			// }
		}
		// if (options.method == 'POST') {
		//   params = Qs.stringify(Object.assign(params, data));
		// } else {
		params = Object.assign(params, options.data);
		// }

		if(options.method.toLowerCase() == 'get' && params!= null &&  Object.keys(params).length > 0){
			path += (path.indexOf('?') > -1 ? '&' : '?') + serialize(params);
			params = null;
		}

		uni.request({
			url: path,
			data: params,
			method: options.method,
			header: header,
			sslVerify: false,
			success: (res) => {
				const code = res.data.code
				const msg = res.data.msg
				if (code === 401) {
					uni.showModal({
						title: '系统提示',
						content: '登录状态已过期，请重新登录',
						success(res) {
							if (res.confirm) {
								store.dispatch('Logout');
							}
						}
					})
				} else if (code === 500) {
					uni.showToast({
						title: msg,
						icon: 'none'
					})
					reject(msg);
				} else if (code !== 200) {
					uni.showToast({
						title: msg,
						icon: 'none'
					})
					reject('error');
				} else {
					resolve(res.data)
				}
			},
			fail: (err) => {
				reject(err);
				isLoading = false;
				if (err.errMsg.indexOf('fail url not in domain list') !== -1) {
					uni.showToast({
						title: '请求无法识别！',
						icon: 'none',
					});
				}
			},
			complete: (res) => {
				if (isLoading) {
					uni.hideLoading();
					isLoading = false;
				}
				if (res.errMsg.indexOf('fail abort statusCode:-1') !== -1) {
					uni.showToast({
						title: '请求失败！',
						icon: 'none',
					});
				}
			},
		});
	});
}

export default {
	// RESOURCE_URL,
	BASE_URL,
	request: requestBase,
	/**
	 * GET请求
	 */
	get(url, data, options) {
		// uni.showLoading({
		//   title: '加载中...',
		//   // mask: true
		// })
		// isLoading = true;
		return requestBase({
			url,
			data,
			method: 'GET',
			...options
		});
	},
	/**
	 * POST 请求
	 */
	post(url, data, options) {
		return requestBase({
			url,
			data,
			method: 'POST',
			...options
		});
	},
	/**
	 * POST formData请求
	 */
	postFormData(url, data, options) {
		return requestBase({
			url,
			data,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			...options
		});
	},
	/**
	 * PUT请求
	 */
	put(url, data, options) {
		return requestBase({
			url,
			data,
			method: 'PUT',
			...options
		});
	},
	/**
	 * DELETE请求
	 */
	del(url, data, options) {
		return requestBase({
			url,
			data,
			method: 'DELETE',
			...options
		});
	},
};
